import hashlib
import json
import os
import time

import requests


class Request:
    def __init__(self):
        self.appkey = "1bN0kRdX8DVPGGvD5UdP"
        self.appSecret = "LzHQEv5nH8umSviagRdhK3lAJrYSMJpqe8QDuO8o"
        self.openid = "kjvb46f04fZ4uHQAbBBM"
        self.api = "https://gateway.rjmart.cn/open/shop"
        self.pre_api = "https://gateway.test.rj-info.com/open/shop"
        module_path = os.path.abspath(__file__)
        self.module_dir = os.path.dirname(module_path)
        if not os.path.exists(f"{self.module_dir}/cx/get_json"):
            os.makedirs(f"{self.module_dir}/cx/get_json")

    # 获取Authorization_Code
    def get_Authorization_Code(self):
        """获取Authorization_Code"""
        url = "https://www.rjmart.cn/auth/oauth/authorize"
        response = requests.get(url=url)
        return response

    # 通过Authorization_Code获取Access_Token
    def ac_get_Access_Token(self):
        """通过Authorization_Code获取Access_Token"""
        url = "https://www.rjmart.cn/auth/oauth/token"
        response = requests.post(url=url)
        return response

    # 通过openid获取Access_Token
    def openid_Access_Token(self):
        """通过openid获取Access_Token"""
        url = "https://www.rjmart.cn/auth/openid/login"
        md5 = hashlib.md5()
        md5.update(self.appSecret.encode("utf-8"))  # 指定需要加密的字符串
        sign = md5.hexdigest()  # 加密后的字符串
        data = {"openid": self.openid, "sign": sign}
        response = requests.post(url=url, data=data)
        results = json.loads(response.content.decode("utf-8"))
        t = time.time()
        results.update({"time": t})
        with open(f"{self.module_dir}/cx/Access_Token_cx.json", mode="w") as f:
            f.write(json.dumps(results))
        return results

    # api基础模板
    def __no_data(self, url, name, data="\{\}"):
        """api基础模板"""
        time_now = time.time()
        with open(f"{self.module_dir}/cx/Access_Token_cx.json") as j:
            ac_json = json.load(j)
        Access_Token = ac_json["access_token"]
        time_acc = ac_json["time"]
        if time_now - time_acc > 600:
            Access_Token = self.openid_Access_Token()["access_token"]
        header = {
            "Authorization": f"Bearer {Access_Token}",
            "Content-Type": "application/json;charset=utf-8",
        }
        json_post_data = self.appSecret + data
        md5 = hashlib.md5()
        md5.update(json_post_data.encode("utf-8"))  # 指定需要加密的字符串
        sign = md5.hexdigest()  # 加密后的字符串
        s_url = f"{self.api}{url}?appkey={self.appkey}&sign={sign}"
        response = requests.post(
            url=s_url,
            **({"data": data.encode("utf-8")} if data else {}),
            headers=header,
            timeout=10,
        )
        results = response.content.decode("utf-8")
        with open(
            f"{self.module_dir}/cx/get_json/{name}.json", mode="w", encoding="utf-8"
        ) as f:
            f.write(results)
        return response

    def settledOgrList(self):
        """查询入驻单位"""
        url = "/openapi/product/settledOgrList"
        name = "settledOgrList"
        return self.__no_data(url, name)

    def updateProductInfoByCode(self, json_data):
        """批量更新（可部分更新）"""
        url = "/openapi/product/updateProductInfoByCode"
        name = "updateProductInfoByCode"
        data = json.dumps(json_data)
        return self.__no_data(url, name, data=data)


def main():
    obj1 = Request()

    test_update = [
        {
            "productNum": "T818517-100ml",
            "desc": """
            <style>
    table{width:100%;border-collapse:collapse;font-family:Arial,sans-serif}td{padding:12px;text-align:left;vertical-align:top;border:1px solid #ddd;background-color:#fff;transition:background-color 0.3s ease}tr > td:first-child span{font-weight:600}tbody tr:hover td{background-color:#f1f1f1}span{display:block;word-wrap:break-word;word-break:break-all;overflow:hidden;text-overflow:ellipsis;-webkit-line-clamp:3;-webkit-box-orient:vertical;line-height:1.5;color:#333}tbody tr:nth-child(even){background-color:#f2f2f2}thead tr td span{text-align:center;color:#409eff;font-size:24px}
    </style><table><thead><tr><td colspan="2"><span>辰星生物</span></td></tr></thead><tbody><tr><td><span>产品中文名</span></td><td><span>磷酸三丁酯</span></td></tr><tr><td><span>产品中文别名</span></td><td><span>磷酸三丁酯 ;磷酸正丁酯,磷酸三正丁酯,三丁基磷酸盐，磷酸三丁脂</span></td></tr><tr><td><span>产品英文名</span></td><td><span>Tributyl phosphate</span></td></tr><tr><td><span>纯度</span></td><td><span>试剂级, 99%</span></td></tr><tr><td><span>颜色</span></td><td><span>无色液体</span></td></tr><tr><td><span>CAS 号</span></td><td><span>126-73-8</span></td></tr><tr><td><span>存储条件</span></td><td><span>室温</span></td></tr><tr><td><span>分子量</span></td><td><span>266.31</span></td></tr><tr><td><span>熔点</span></td><td><span>-79 °C</span></td></tr><tr><td><span>沸点</span></td><td><span>180-183 °C/22 mmHg(lit.)</span></td></tr><tr><td><span>闪点</span></td><td><span>145 °C</span></td></tr><tr><td><span>密度</span></td><td><span>0.979 g/mL at 25 °C(lit.)</span></td></tr><tr><td><span>折光率</span></td><td><span>n20/D 1.424(lit.)</span></td></tr></tbody></table>
            """
        }
    ]
    res = obj1.updateProductInfoByCode(test_update)
    print(res.json)


if __name__ == "__main__":
    main()
